<?php

namespace App\Service;


use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
use Psr\Http\Message\ResponseInterface;

class HttpService extends BaseService
{

    /**
     * @Inject()
     * @var ClientFactory
     */
    protected $clientFactory;

    private $client;

    public function __construct()
    {
        $this->client = $this->clientFactory->create();

    }


    /**
     * http get 请求
     * @param string $url 地址
     * @param array $query get 参数
     * @param array $header 添加的header
     * @return false|mixed
     */
    public function get(string $url, array $query = [], array $header = [])
    {
        $options = [
            'headers' => $header,
            'query' => $query
        ];
        try {
            $result = $this->client->get($url, $options)->getBody()->getContents();
            return json_decode($result, true);
        } catch (GuzzleException $e) {
            recordExceptionLog('httpGet', $e->getMessage());
            return false;
        }
    }

    /**
     * http  post
     * @param string $url
     * @param array $params  post -> form_params get -> query
     * @param array $header
     * @return false|mixed
     */
    public function post(string $url, array $params = [], array $header = [])
    {
        $options = [
            'headers' => $header,
            'json' => $params,
        ];
        try {
            $result = $this->client->post($url, $options);
            $results = $result->getBody()->getContents();
            $httpLogData = [
                'url'=>$url,
                'param'=>json_encode($options),
                'results'=>json_encode($results),
                'status_code'=>$result->getStatusCode(),
            ];

            return json_decode($results, true);
        } catch (GuzzleException $e) {
            recordExceptionLog('httpGet', $e->getMessage());
            return false;
        }
    }


    /**
     * 通用请求
     * @param string $url
     * @param array $options
     * @param string $method
     * @return false|ResponseInterface
     */
    public function request(string $url,array $options, string $method = 'GET')
    {

        try {
            $result = $this->client->request($method, $url, $options);
            return json_decode($result->getBody()->getContents(),true);
        } catch (GuzzleException $e) {
            var_dump($e->getMessage());
            recordExceptionLog('request', $e->getMessage());
            return false;
        }

    }


}
